package com.springboot.study.controller;

import com.springboot.study.domain.AccessToken;
import com.springboot.study.util.WxJsUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class WechatController {
    private static final String APPID = "wxafd5b5e8c00ca67f";
    private static final String SECRET = "7345d214e23c6d88c0b0cbab3866ad25";

    @RequestMapping("/getWxConfig")
    public Map<String, Object> getWxConfig(ServletRequest request){
         String jsapi_ticket;
        //获取Unix时间戳
        long timestamp = System.currentTimeMillis() / 1000L;
        WxJsUtils wxJsUtils = new WxJsUtils();

        //获取appId
        //获取页面路径(前端获取时采用location.href.split('#')[0]获取url)
        String url = request.getParameter("url");

        //判断ticket是否有效
        if(wxJsUtils.checkTicketExpiresin()){//从缓存中获取ticket
             jsapi_ticket = wxJsUtils.cacheTickect();
        }else {
            //获取access_token
            AccessToken access_token=wxJsUtils.getAccessToken(APPID,SECRET);
            //获取ticket
             jsapi_ticket = wxJsUtils.getTickect(access_token.getAccessToken());
        }

        String noncestr = UUID.randomUUID().toString();
        //获取签名
        String signature = wxJsUtils.signature(jsapi_ticket, timestamp, noncestr, url);

        //创建Map用于创建签名串
        Map<String, Object> params = new HashMap<>();
        params.put("jsapi_ticket", jsapi_ticket);
        params.put("timestamp", timestamp);
        params.put("noncestr", noncestr);
        params.put("url", url);

        //得到签名再组装到Map里
        params.put("signature", signature);
        //传入对应的appId
        params.put("appId", APPID);
        return params;
    }
}
